package com.imooc.springmvc3.advice;

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * 使用@ExceptionHandler演示处理全局异常,更加人性化的将异常输出给用户
 *
 * ControllerAdvice:声明一个控制器建言,
 * ControllerAdvice注解组合了@Component注解,所以自动注册为sping的ben
 * Created by joe on 16-8-12.
 */
@ControllerAdvice
public class ExceptionHandlerAdvice {
    /**
     *
     *  @ExceptionHandler:在此定义全局处理,
     *  通过value属性可过滤拦截的条件,此处我们拦截所有的Exception
     * @param exception
     * @param request
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ModelAndView exception(Exception exception, WebRequest request){
        ModelAndView modelAndView = new ModelAndView("error");//error的页面
        modelAndView.addObject("errorMessage",exception.getMessage());
        return modelAndView;
    }

    /**
     *此处使用@ModelAttribute注解将键值对添加到全局,所有注解的@RequestMapping的方法可以获得此键值对
     * @param model
     */
    @ModelAttribute
    public void addAttributes(Model model){
        model.addAttribute("msg","额外信息");
    }

    /**
     * 通过@InitBinder注解定制WebDataBinder
     * @param webDataBinder
     */
    @InitBinder
    public void initBinder(WebDataBinder webDataBinder){
        webDataBinder.setDisallowedFields("id");
    }
}
